package com.itheima.service.impl;

import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectByClassId(Integer classId) {
        List<User> userList = userMapper.selectByClassId(classId);
        if (userList == null) return null;

        List<User> groupsIntegralList = userMapper.selectGroupsIntegral(classId);
        if (groupsIntegralList == null) return null;

        for (User userGroupIntegral : groupsIntegralList) {
            if (userGroupIntegral == null) continue;
            Integer groupId = userGroupIntegral.getGroupId();
            Integer groupIntegral = userGroupIntegral.getGroupsIntegral();
            if (Objects.isNull(groupId) && Objects.isNull(groupIntegral)) continue;
            for (int i = 0; i < userList.size(); i++) {
                User user = userList.get(i);
                if (Objects.isNull(user)) continue;
                if (Objects.isNull(user.getGroupId())) continue;
                if (groupId == user.getGroupId()) user.setGroupsIntegral(groupIntegral);
            }
        }
        return userList;
    }

    @Override
    public boolean updateIntegral(User user) {
        return userMapper.updateIntegral(user) > 0;
    }

    @Override
    public boolean updateResetIntegral(Integer groupId) {
        return userMapper.updateResetIntegral(groupId) > 0;
    }
}
